package com.example.service;

import com.example.annotation.Task;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 任务服务类，包含需要在线程池中执行的耗时任务
 */
@Service
public class TaskService {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 每秒钟输出一次当前时间，持续1分钟
     */
    @Task(name = "timePrintTask")
    public void printTimeEverySecond() {
        System.out.println("开始执行时间打印任务...");

        for (int i = 0; i < 60; i++) {
            try {
                // 输出当前时间
                String currentTime = sdf.format(new Date());
                System.out.println("当前时间: " + currentTime + " (" + Thread.currentThread().getName() + ")");

                // 休眠1秒
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("任务被中断: " + e.getMessage());
                Thread.currentThread().interrupt();
                break;
            }
        }

        System.out.println("时间打印任务执行完毕");
    }

    /**
     * 倒计时任务，从60秒开始倒计时
     */
    @Task(name = "countdownTask")
    public void countdownFromSixty() {
        System.out.println("开始执行倒计时任务...");

        for (int i = 60; i > 0; i--) {
            try {
                System.out.println("倒计时: " + i + "秒 (" + Thread.currentThread().getName() + ")");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("任务被中断: " + e.getMessage());
                Thread.currentThread().interrupt();
                break;
            }
        }

        System.out.println("倒计时任务执行完毕！");
    }
}
